package org.example.medical.service.impl;

import org.apache.ibatis.annotations.Mapper;
import org.example.medical.Mapper.CostRecordMapper;
import org.example.medical.Mapper.VisitRecordMapper;
import org.example.medical.entity.VisitRecord;
import org.example.medical.service.VisitRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class VisitRecordServiceImpl implements VisitRecordService {

    @Autowired
    private VisitRecordMapper visitRecordMapper;
    @Autowired
    private CostRecordMapper costRecordMapper;
    @Override
    public List<VisitRecord> getVisitRecords(String patientName, String doctorName, String type, LocalDate visitTime, String department, int page, int size) {
        int offset = (page - 1) * size;
        return visitRecordMapper.selectByPageAndFilters(
                patientName,
                doctorName,
                type,
                visitTime != null ? visitTime.toString() : null,
                department,
                offset,
                size
        );
    }

    @Override
    public void addVisitRecord(VisitRecord visitRecord) {
        visitRecordMapper.insertVisitRecord(visitRecord);
    }

    @Override
    public void updateVisitRecord(VisitRecord visitRecord) {
        visitRecordMapper.updateVisitRecord(visitRecord);

    }

    @Override
    public void deleteVisitRecord(Long recordId) {
        List<Long> costIds = costRecordMapper.getCostIdsByRecordId(recordId);
        if (costIds != null && !costIds.isEmpty()){
            costRecordMapper.batchSoftDeleteCostRecords(costIds);
        }

        visitRecordMapper.deleteVisitRecord(recordId);
    }

    @Override
    public void batchSoftDeleteVisitRecords(List<Long> recordIds) {
        for (Long recordId : recordIds){
            List<Long> costIds = costRecordMapper.getCostIdsByRecordId(recordId);
            if (costIds != null && !costIds.isEmpty()){
                costRecordMapper.batchSoftDeleteCostRecords(costIds);
            }
        }
        visitRecordMapper.batchSoftDeleteVisitRecords(recordIds);
    }
}
